import useModal from '@/hooks/modalHook'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {throttle} from '@/libs/debounce'
import {VNodeRef} from 'vue'
import {IconImg} from '../image'

const ToTop = defineComponent({
  setup(props, ctx) {
    const {store} = useGlobalAPI()

    // 回到顶部按钮的ref
    const toTopRef = ref<VNodeRef | undefined>(undefined)

    // 是否显示回到顶部按钮
    const visible = ref(false)

    // 处理回到顶部按钮的父元素滚动事件
    const handleDomScroll = throttle((e: Event) => {
      if (e.type === 'scroll') {
        if (visible.value) {
          if ((e.target as HTMLElement).scrollTop < (e.target as HTMLElement).offsetHeight * 0.1) {
            visible.value = false
          }
        } else {
          if ((e.target as HTMLElement).scrollTop >= (e.target as HTMLElement).offsetHeight * 0.1) {
            visible.value = true
          }
        }
      }
    }, 300)

    function openEventListener() {
      if (toTopRef.value) {
        toTopRef.value.parentNode.addEventListener('scroll', handleDomScroll)
      }
    }
    function closeEventListener() {
      if (toTopRef.value) {
        toTopRef.value.parentNode.removeEventListener('scroll', handleDomScroll)
      }
    }

    // 回到顶部
    function toTop() {
      if (toTopRef.value) {
        store.dispatch('layoutMain/MAINSCROLLTOTOP', toTopRef.value.parentNode.id)
      }
    }

    onMounted(() => {
      openEventListener()
    })
    onUnmounted(() => {
      closeEventListener()
    })
    return () => (
      <div
        title='回到顶部'
        ref={toTopRef}
        class={[
          'toTop fixed bottom-60 right-60 w-46 h-46 rounded-full shadow-md z-50 overflow-hidden',
          visible.value ? '' : 'hidden'
        ]}
        onClick={toTop}
      >
        <IconImg imgName='toTop' class='toTop-icon w-42 h-42'></IconImg>
      </div>
    )
  }
})

export default ToTop
